package com.service.gmall.product.service.impl;

import com.service.gmall.common.util.DateUtil;
import com.service.gmall.product.config.minio.MinioProperties;
import com.service.gmall.product.service.FileuploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author alpha
 * @className: FileuploadServiceImpl
 * @date 2022/8/25 10:11
 * @Description
 */
@Service
public class FileuploadServiceImpl implements FileuploadService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;

    //todo 等待统一异常处理
    @Override
    public String upload(MultipartFile file) throws Exception {
        //判断桶是否存在
        boolean exists = minioClient.bucketExists(minioProperties.getBucketName());
        if (!exists) {
            minioClient.makeBucket(minioProperties.getBucketName());
        }

        // 使用putObject上传一个文件到存储桶中。
        String dateStr = DateUtil.formatDate(new Date());
        String filename = UUID.randomUUID().toString().replace("-", "")
                + "_" + file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String contentType = file.getContentType();
        PutObjectOptions options = new PutObjectOptions(file.getSize(), -1L);
        options.setContentType(contentType);
        minioClient.putObject(minioProperties.getBucketName(),
                dateStr + "/" + filename,
                inputStream,
                options);

        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + dateStr + "/" + filename;
        return url;
    }
}
